package cn.schoolwow.util.module.compare.instanceList.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.compare.instanceList.UpdateInstanceListCompare;
import cn.schoolwow.util.domain.query.instance.QueryInstance;
import cn.schoolwow.util.module.compare.instanceList.domain.CompareInstanceListQueryOption;

import java.util.ArrayList;
import java.util.List;

public class SetAddAndUpdateCompareListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        CompareInstanceListQueryOption compareInstanceListQueryOption = (CompareInstanceListQueryOption) flowContext.checkData("compareInstanceListQueryOption");

        List addCompareList = new ArrayList();
        List<UpdateInstanceListCompare> updateInstanceListCompareList = new ArrayList();
        for(Object afterInstance:compareInstanceListQueryOption.afterInstanceList){
            Object afterAddValue = QueryInstance.newQuery(afterInstance)
                    .execute()
                    .getMultipleFieldValue(compareInstanceListQueryOption.addCheckFieldNames);

            Object afterUpdateValue = QueryInstance.newQuery(afterInstance)
                    .execute()
                    .getMultipleFieldValue(compareInstanceListQueryOption.updateCheckFieldNames);

            boolean exist = false;
            for(Object beforeInstance:compareInstanceListQueryOption.beforeInstanceList){
                Object beforeAddValue = QueryInstance.newQuery(beforeInstance)
                        .execute()
                        .getMultipleFieldValue(compareInstanceListQueryOption.addCheckFieldNames);

                Object beforeUpdateValue = QueryInstance.newQuery(beforeInstance)
                        .execute()
                        .getMultipleFieldValue(compareInstanceListQueryOption.updateCheckFieldNames);

                if(beforeAddValue.equals(afterAddValue)){
                    //已存在,判断是否有更新
                    if(!beforeUpdateValue.equals(afterUpdateValue)){
                        UpdateInstanceListCompare updateCompare = new UpdateInstanceListCompare();
                        updateCompare.beforeInstance = beforeInstance;
                        updateCompare.afterInstance = afterInstance;
                        updateInstanceListCompareList.add(updateCompare);
                    }
                    exist = true;
                }
            }
            if(!exist){
                //新增
                addCompareList.add(afterInstance);
            }
        }

        flowContext.putReturnData("addCompareList", addCompareList);
        flowContext.putReturnData("updateInstanceListCompareList", updateInstanceListCompareList);
    }

    @Override
    public String name() {
        return "设置新增和更新比较实例列表";
    }
}
